package com.zoweunion.mechanic.util.hefeng;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zoweunion.mechanic.config.HeFengConfig;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class HeFengWeather {
    private final Logger logger = LoggerFactory.getLogger(HeFengWeather.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HeFengConfig heFengConfig;


    private String weatherConventional = "https://free-api.heweather.net/s6/weather/now?location={location}&key={key}";

    /**
     *
     * @param location  longitude + "," + latitude
     * @return
     * @throws MyException
     */
    public Map<String, Object> getWeatherNow(String location) throws MyException {
        Map<String, String> params = new HashMap<>();
        params.put("location", location);
        params.put("key", heFengConfig.getKey());
        String resBody = restTemplate.getForObject(weatherConventional, String.class, params);
        Map<String, Object> heWeather = JSON.parseObject(resBody, new TypeReference<Map<String, Object>>() {
        });
        if (heWeather == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "天气服务不可用");
        }
        Map<String, Object> bodyMap = (JSONObject) ((JSONArray) heWeather.get("HeWeather6")).get(0);
        if (!"ok".equals(bodyMap.get("status").toString())) {
            logger.error("请求和风天气接口报错：" + HeFengConstants.ErrorCode.getDescriptionByStatus(bodyMap.get("status").toString()));
            throw new MyException(Constants.CODE_HANDEL_FAILED, "请求天气服务接口报错");
        }
        return (JSONObject) bodyMap.get("now");
    }
}
